package com.nxlv2.nomad.accessdb.dao.jdbc;

import com.nxlv2.nomad.accessdb.dao.DAOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ConnectionManager implements IConnectionMySQL {

    private static final Logger logger = LoggerFactory.getLogger(ConnectionManager.class);
    private Connection connexion = null;
    private final String keyAES = "nomadKey";

    @Override
    public Connection creerConnection() throws DAOException {
        logger.debug("Getting connection: driver={}/url={}/login={}/pswd={}", DRIVER_NAME, DB_URL, DB_LOGIN, DB_PASSWORD);
        
        try {
            Class.forName(DRIVER_NAME).newInstance();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            logger.error("Problème avec le driver JDBC", e);
            throw new DAOException("Cannot load jdbc driver.", e);
        }
        try {
            connexion = DriverManager.getConnection(IConnectionMySQL.DB_URL, IConnectionMySQL.DB_LOGIN, IConnectionMySQL.DB_PASSWORD);
        } catch (SQLException e) {
            logger.error("Connection BDD impossible", e);
            throw new DAOException("Connection BDD impossible", e);
        }
        return connexion;
    }

    @Override
    public void executerRequete(String requete) {
        Connection con = creerConnection();
        try {
            Statement stmt = con.createStatement();
            stmt.executeUpdate(requete);
        } catch (SQLException e) {
            throw new DAOException("Exécution de la requête impossible", e);
        }
        try {
            con.close();
        } catch (SQLException ex) {
            throw new DAOException("Impossible de fermer la connexion", ex);
        }
    }

    @Override
    public ResultSet executerRequeteSelect(String requete) {
        ResultSet rst = null;
        try {
            Statement stmt = connexion.createStatement();
            rst = stmt.executeQuery(requete);
        } catch (SQLException e) {
            throw new DAOException("Exécution de la requête select impossible", e);
        }
        return rst;
    }

    @Override
    public void fermerConnection() {
        try {
            connexion.close();
        } catch (SQLException e) {
            throw new DAOException("Impossible de fermer la connection", e);
        }
    }

    @Override
    public String getKeyAES() {
        return keyAES;
    }
}